import React, { Component } from 'react'
import { connect } from 'react-redux'
import UrlPattern from 'url-pattern'
import { message, Icon, Card } from 'antd'

import OnlineLanguageAnswer from './assignment/online-language-answer'
import * as actions from '../actions/online-language-answer'

import { studentAnswerPageUrl } from '../constant/constant-url'
import { FormattedMessage } from 'react-intl'
import { convertContent } from '../constant/lang-util'

class StudentAnswerPage extends Component {
  constructor () {
    super()
    this.state = {
      assignmentId: 0,
      quizId: 0
    }
  }

  componentDidMount () {
    const pattern = new UrlPattern(studentAnswerPageUrl)
    const urlParams = pattern.match(this.props.location.pathname)
    this.setState({
      paperId: urlParams.paperId,
      assignmentId: urlParams.assignmentId,
      quizId: urlParams.quizId
    })
    this.props.studentGetOnlineLanguageAnswer(urlParams, this.renderErrorMessage)
  }

  renderErrorMessage () {
    return message.error(convertContent('完成作业才能看呦'))
  }

  getAnswerFile () {
    const { programCenterUrl } = this.props.settings
    window.location.assign(`${programCenterUrl}/api/v2/onlineLanguageQuizzes/${this.state.quizId}/answerFile`)
  }

  render () {
    const { onlineLanguage } = this.props

    return (<div>
      <Card title={<a onClick={() => window.history.back()}><Icon type='arrow-left' /><FormattedMessage id='返回我的作业' /></a>} noHovering bordered={false}>
        <OnlineLanguageAnswer isStudent onlineLanguageQuiz={onlineLanguage} getAnswerFile={this.getAnswerFile.bind(this)} />
      </Card>
    </div>)
  }
}

const mapStateToProps = (state) => {
  return {
    user: state.user,
    onlineLanguage: state.onlineLanguageAnswer,
    settings: state.settings
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    studentGetOnlineLanguageAnswer: (data, callback) => dispatch(actions.studentGetOnlineLanguageAnswer(data, callback))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(StudentAnswerPage)
